package com.github.baichuan.iot.gateway.handler;

import com.github.baichuan.iot.gateway.context.DeviceContext;
import com.github.baichuan.iot.gateway.context.DeviceContextCache;
import com.github.baichuan.iot.protocol.codec.MessageDecodeContext;
import com.github.baichuan.iot.protocol.echo.Responder;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 入站消息自动应答处理器
 */
@Slf4j
@ChannelHandler.Sharable
public class ResponderHandler extends ChannelInboundHandlerAdapter {
    private Responder responder;

    private DeviceContextCache cache;

    public ResponderHandler(Responder responder, DeviceContextCache cache){
        this.responder = responder;
        this.cache = cache;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        MessageDecodeContext inbound = (MessageDecodeContext) msg;
        DeviceContext context = cache.get(inbound.getDevice());

        responder.ack(inbound).stream().forEach(outbound -> {
            if(context.isDebug()){
                log.info("[DEBUG:{}] device outbound cmd 0x{} with payload {} for echo inbound cmd 0x{} with payload {}", inbound.getDevice(),
                        Integer.toHexString(outbound.getId()),
                        ByteBufUtil.hexDump(outbound.getPayload()),
                        Integer.toHexString(inbound.getId()),
                        ByteBufUtil.hexDump(inbound.getPayload()));
            }
            ctx.pipeline().writeAndFlush(outbound);
        });

        ctx.fireChannelRead(msg);
    }

}
